<?PHP

require_once __DIR__.DIRECTORY_SEPARATOR.'functions.php';

function upload_tmp_res($file, $type = 'image')
{
    $url = WXURL.'media/upload?access_token='.ACCESS_TOKEN;
    $url .= '&type='.$type;

    $data = array('file' => curl_file_create($file));

    $json = json_decode(kyo_curl($url, $data, 'POST'));

    if (isset($json->media_id))
        return $json->media_id;

    return FALSE;
}

function get_tmp_res($id, $savepath)
{
    $url = WXURL.'media/get?access_token='.ACCESS_TOKEN;
    $url .= '&media_id='.$id;

    $r = kyo_curl($url, null, 'GET', null, TRUE);

    if (isset($r['info'])) {
        file_put_contents($savepath, $r['data']);
        return $r['info'];
    }

    return $r;
}

function upload_image($file)
{
    $url = WXURL.'media/uploadimg?access_token='.ACCESS_TOKEN;
    $data = array('file' => curl_file_create($file));

    $curl_data = kyo_curl($url, $data, 'POST');
    $json = json_decode($curl_data);

    if (isset($json->url))
        return $json->url;

    return FALSE;
}

function upload_media($file, $type, $title = null, $info = null)
{
    $url = WXURL.'material/add_material?access_token='.ACCESS_TOKEN;
    $url .= '&type='.$type;

    $data = array('file' => curl_file_create($file));

    if ($type == 'video' && $title !== null && $info !== null)
        $data['description'] = '{"title":"'.$title.'", "introduction":"'.$info.'"}';

    $curl_data = kyo_curl($url, $data, 'POST');
    print_r($curl_data);
    $json = json_decode($curl_data);

    if (isset($json->media_id))
        return $json->media_id;

    return FALSE;
}

// print_r(upload_image('/www/upload.png'));
// print_r(upload_media('/www/upload.png', 'image'));
// print_r(upload_media('/www/php.mp4', 'video', '课程', 'PHP课程'));


get_tmp_res('4Z3ety70_9NciwuNfWIrk2WvmEO0SVoCLx3hBHdyDfnyNbe2F8srwOIO0DdIY2Ft', '/dev/shm/wx.png');

